import { useModel } from "umi";
import { useEffect } from "react";
import { useReactive } from "ahooks";
import compress from "gql-compress";

const useInstitution = (oiUuid) => {
    const { graphqlFetch } = useModel("global");

    const state = useReactive({
        loading: false,
        store: {},
    });

    // 加载所有部门信息, 用树的数据格式
    const loadInstitution = async (oiUuid) => {
        state.loading = true;
        let res = await graphqlFetch({
            query,
            variables: {
                oiUuid,
            },
        });
        if (!res) return;
        const { children } = res.a;
        let store = {
            ...res.a,
            id: oiUuid,
            type: "store",
            children: children.nodes.map((item) => ({
                ...item,
                id: item.reUuid,
                type: "person",
            })),
        };
        state.store = store;
        state.loading = false;
        return store;
    };

    useEffect(() => {
        oiUuid && loadInstitution(oiUuid);
    }, [oiUuid]);

    return { ...state, loadInstitution };
};

const query = compress(`query MyQuery($oiUuid: UUID!) {
    a: organizationInstitutionByOiUuid(oiUuid: $oiUuid) {
        asInfo
        crInfo
        maInfo
        mpInfo
        oiCity
        oiComm
        oiDesc
        oiDist
        oiEsta
        oiLeve
        oiName
        oiPaid
        oiPhon
        oiPrin
        oiRoot
        oiStat
        oiStre
        oiType
        oiUuid
        oiZoja
        otInfo
        ptInfo
        pyName
        upInfo
        oiAddr
        children: organizationInstitutionsMembersByOiUuid {
            nodes {
                reUuid
                reType
                oiUuid
                staff: organizationStaffByOsUuid {
                    osUuid
                    osName
                }
                member: organizationMemberByOmUuid {
                    omUuid
                    omName
                }
                position: organizationPositionByOpUuid {
                    opUuid
                    opName
                }
            }
        }
    }
}`);

export default useInstitution;
